package com.sunxd.zstudy.juc.T19_container.concurrent;

import java.util.List;
import java.util.Random;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.stream.Stream;

/**
 * 写时复制 写的时候枷锁，读的时候不枷锁
 * 原理 + synchronized + copy
 *
 * 适合写少读多的情况
 * @author: 作者名称
 * @date: 2021-09-10 11:47
 **/
public class T01_CopyOnWriteList {
    public static void main(String[] args) {
        List<String> list= new CopyOnWriteArrayList<>();
        Random r= new Random();
        Thread[] threads = new Thread[100];
        for (int i = 0; i < threads.length; i++) {
            threads[i] = new Thread(()->{
                for (int j = 0; j < 1000; j++) {
                    list.add("a"+r.nextInt(10000));
                }
            });
        }
        long start = System.currentTimeMillis();
        Stream.of(threads).forEach( x -> {
            x.start();
        });
        for (Thread thread : threads) {
            try {
                thread.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        long end = System.currentTimeMillis();
        System.out.println(end - start);
        System.out.println(list.size());

    }
}
